package com.jzr.bedside.service

import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.blankj.utilcode.utils.LogUtils
import com.google.gson.Gson
import com.jzr.bedside.base.BaseEvenBus
import com.jzr.bedside.bean.WebSocketReqBean
import com.jzr.bedside.bean.WebSocketSendBean
import com.jzr.bedside.utils.PreferUtil
import com.jzr.netty.common.base.BaseMsg
import com.jzr.netty.common.base.MsgType
import com.zhangke.websocket.SimpleListener
import com.zhangke.websocket.SocketListener
import com.zhangke.websocket.WebSocketHandler
import com.zhangke.websocket.response.ErrorResponse
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.nio.ByteBuffer

class WebSocketServer : Service() {


    override fun onCreate() {
        super.onCreate()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        WebSocketHandler.getDefault().addListener(socketListener)
        WebSocketHandler.getDefault().reconnect()

    }

    private val socketListener: SocketListener = object : SimpleListener() {
        override fun onConnected() {
            val sendText = WebSocketSendBean()
//            sendText.deviceNo= Build.SERIAL
            sendText.deviceNo= PreferUtil.getInstance().bedCode
            sendText.cmd = "lgn"
            WebSocketHandler.getDefault().send(Gson().toJson(sendText))

        }

        override fun onConnectFailed(e: Throwable) {
            if (e != null) {

            } else {

            }

        }

        override fun onDisconnect() {

        }

        override fun onSendDataError(errorResponse: ErrorResponse) {
            errorResponse.release()
        }

        override fun <T> onMessage(message: String, data: T) {

            val webReq=  Gson().fromJson(message,WebSocketReqBean::class.java)
            when(webReq.cmd){
                "reload"->{
                    EventBus.getDefault().post(BaseEvenBus(BaseEvenBus.RELOAD))
                }
            }
                    LogUtils.e("EEEE",message)
        }

        override fun <T> onMessage(bytes: ByteBuffer, data: T) {
            LogUtils.e("AAAAA")
        }

    }

    fun senMessage(text: String?) {
        WebSocketHandler.getDefault().send(text)
    }


    @Subscribe
    fun getEventBus(baseMsg: BaseEvenBus) {

    }

    override fun onDestroy() {
        super.onDestroy()
        WebSocketHandler.getDefault().removeListener(socketListener)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

}